<template>
    <h1>3D 浸入式浏览</h1>
    <!-- ✅ 实时显示相机和模型位置 -->
    <div id="info">
        相机: {{ cameraPos }}<br>
        模型: {{ modelPos }}
    </div>
    <div id="three-container"></div>
    <!-- 可选：进度条 -->
    <!-- <div id="progress-bar" :style="{ width: progress * 100 + '%' }"></div> -->
</template>

<script setup>
import { ref, onMounted } from 'vue';
import * as THREE from 'three';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js'; // 仅用于调试路径，最终可移除

// 场景、相机、渲染器
const scene = new THREE.Scene();
let camera, renderer;

// 动画变量
let t = 0;           // 当前路径进度 0~1
let targetT = 0;     // 平滑目标进度
const totalSteps = 100; // 滚动多少步走完全程
let curve;           // 相机路径
let modelCenter = new THREE.Vector3(0, 0, 0); // 模型中心

const cameraPos = ref('0,0,0');
const modelPos = ref('0,0,0');
let model; // 保存模型引用

onMounted(() => {
    initThree();
    load3d();
});

// 初始化 Three.js
function initThree() {
    // 相机
    camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 10000); // 扩大 far
    camera.position.set(0, 0, 20); // 初始位置

    // 渲染器
    renderer = new THREE.WebGLRenderer({ antialias: true });
    renderer.setSize(window.innerWidth, window.innerHeight);
    renderer.setPixelRatio(window.devicePixelRatio); // 高清屏适配

    const container = document.getElementById('three-container');
    container.appendChild(renderer.domElement);

    // 🔁 添加辅助控制（仅用于调试路径，上线可删除）
    const debugControls = new OrbitControls(camera, renderer.domElement);
    debugControls.enabled = false; // 默认关闭，方便测试路径

    // 添加灯光
    const ambientLight = new THREE.AmbientLight(0xffffff, 0.5);
    const directionalLight = new THREE.DirectionalLight(0xffffff, 1);
    directionalLight.position.set(5, 5, 5);
    scene.add(ambientLight, directionalLight);

    // 启动渲染循环
    animate();
}

// 创建相机飞行路径（根据你的模型调整）
function createCameraPath() {
    // ✅ 根据你的模型大小调整这些点   红色 = X 轴（右） 🟢 绿色 = Y 轴（上） 🔵 蓝色 = Z 轴（前）
    curve = new THREE.CatmullRomCurve3([
        new THREE.Vector3(90, 500, 400),     // 上方俯视
        new THREE.Vector3(250, 300, 300),     // 上方俯视
        new THREE.Vector3(300, 200, 200),     // 上方俯视
        new THREE.Vector3(400, 100, 140),     // 上方俯视
        new THREE.Vector3(300, 150, 200),     // 另一侧
        new THREE.Vector3(200, 150, 250),     // 另一侧
        new THREE.Vector3(200, 150, 300),     // 另一侧
        new THREE.Vector3(100, 150, 400),     // 另一侧
        new THREE.Vector3(100, 150, 500),     // 另一侧
        new THREE.Vector3(200, 100, 550),   // 起点：远处侧面
        new THREE.Vector3(100, 50, 100),    // 绕到侧面
        new THREE.Vector3(150, 100, 100),       // 正面靠近

        new THREE.Vector3(100, 100, 200),     // 上方俯视
        new THREE.Vector3(0, 8, 80),      // 低角度仰视
        new THREE.Vector3(-20, 10, 30),   // 回到起点（可选）


    ], false, 'catmullrom', 0.2);

    // 可视化路径（调试用）
    const points = curve.getPoints(100);
    const geometry = new THREE.BufferGeometry().setFromPoints(points);
    const material = new THREE.LineBasicMaterial({ color: 0xff0000, transparent: true, opacity: 0.3 });
    const curveObject = new THREE.Line(geometry, material);
    // scene.add(curveObject); // 取消注释可看到红色路径
}

// 监听滚轮
window.addEventListener('wheel', (event) => {
    if (event.deltaY > 0) {
        targetT = Math.min(1, targetT + 1 / totalSteps); // 向下滚 → 前进
    } else {
        targetT = Math.max(0, targetT - 1 / totalSteps); // 向上滚 → 后退
    }
});

// 加载模型
function load3d() {
    const loader = new GLTFLoader();

    loader.load(
        '/3d/dm_book.glb',
        (gltf) => {
            console.log('✅ 模型加载成功');

            // 强制双面渲染
            gltf.scene.traverse((child) => {
                if (child.isMesh) {
                    child.material.side = THREE.DoubleSide;
                    child.material.transparent = false;
                    child.material.opacity = 1;
                }
            });

            // 设置位置和缩放
            gltf.scene.position.set(0, 0, 0);
            gltf.scene.scale.set(10, 10, 10);

            // 计算模型中心
            const box = new THREE.Box3().setFromObject(gltf.scene);
            modelCenter = box.getCenter(new THREE.Vector3());

            gltf.scene.position.set(0, 0, 0);
            gltf.scene.scale.set(10, 10, 10);
            model = gltf.scene; // 保存引用

            // 添加模型
            scene.add(gltf.scene);

            // ✅ 模型加载后创建路径
            createCameraPath();
            updateCamera(0); // 初始化相机位置
        },
        undefined,
        (error) => {
            console.error('❌ 加载失败:', error);
        }
    );
}

// 更新相机位置
function updateCamera(t) {
    if (!curve) return;

    const point = curve.getPoint(t);
    camera.position.copy(point);

    // 看向模型中心
    camera.lookAt(modelCenter);
}

// 动画循环
function animate() {
    requestAnimationFrame(animate);

    // 平滑插值
    t += (targetT - t) * 0.1;
    updateCamera(t);

    renderer.render(scene, camera);

    // ✅ 实时更新坐标显示
    if (model) {
        modelPos.value = `${model.position.x.toFixed(2)}, ${model.position.y.toFixed(2)}, ${model.position.z.toFixed(2)}`;
    }
    cameraPos.value = `${camera.position.x.toFixed(2)}, ${camera.position.y.toFixed(2)}, ${camera.position.z.toFixed(2)}`;

    renderer.render(scene, camera);
}
</script>

<style scoped>
#three-container {
    width: 100%;
    height: 90vh;
    background: #000;
    position: relative;
    overflow: hidden;
    touch-action: none;
}

h1 {
    color: white;
    text-align: center;
    margin-bottom: 0;
}

/* 可选：添加进度条 */
/* #progress-bar {
    position: fixed;
    top: 0;
    left: 0;
    height: 3px;
    background: #00ff88;
    z-index: 1000;
    transition: width 0.1s;
} */

#info {
    position: fixed;
    top: 10px;
    left: 10px;
    color: white;
    font-family: monospace;
    font-size: 14px;
    background: rgba(0,0,0,0.7);
    padding: 10px;
    border-radius: 4px;
    z-index: 100;
}
</style>